'''
Case Type： 文件目录
Case Name： 主设备事务执行时删除主机pg_log
Create At:  2020/07/23
Owner    :  @li-xin12345
Descption:  1. 备份pg_log文件 2. 执行事务 3. 在执行事务的过程中删除主机pg_log文件 4. 备机进行数据查询 5. 恢复pg_log文件
'''

import os
import sys
import unittest
import time
from yat.test import Node
from testcase.utils.CommonSH import *
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.CommonSH import *

from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread
from testcase.utils.Common import Common

logger = Logger()


class IndexFileDamaged(unittest.TestCase):
    logger.info('------------Opengauss_Reliability_Dbsys_Case184.py start------------')
    primaryNode = Node(node='PrimaryDbUser')
    standbyNode = Node(node='Standby1DbUser')
    primaryRootNode = Node(node='PrimaryRoot')
    standby1RootNode = Node(node='Standby1Root')
    DB_ENV_PATH = macro.DB_ENV_PATH
    DB_LOG_PATH = macro.PG_LOG_PATH
    Constant = Constant()
    sh_primy = CommonSH('PrimaryDbUser')
    sh_stadb = CommonSH('Standby1DbUser')
    com = Common('PrimaryRoot')

    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def test_Index_file_damaged(self):
        logger.info('--------------start tpcc--------------------------- ')
        tpcc_thread = ComThread(self.com.startTPCC, args=(self.primaryRootNode, macro.TPCC_PATH))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()

        logger.info('----------------------------删除pg_log文件-----------------------------')
        excute_cmd = f'cp -r {self.DB_LOG_PATH} {self.DB_LOG_PATH}.testBAK; rm -rf {self.DB_LOG_PATH}'
        logger.info(excute_cmd)
        msg = self.primaryNode.sh(excute_cmd).result()
        logger.info(msg)

        logger.info('--------------check tpcc result--------------------------- ')
        tpcc_thread.join(int(macro.TPCC_RUN_MAX_TIME) * 2)
        tpcc_result = tpcc_thread.get_result()
        logger.info(tpcc_result)
        self.assertIn(self.Constant.TPCC_SUCCESS_MSG, tpcc_result)

        logger.info('---------------------判断备机pg_log更新是否正常-------------------')
        result = self.standby1RootNode.sh(f'find {self.DB_LOG_PATH} - mmin - 2').result()
        logger.info(result)
        self.assertIn('postgresql', result)

    def tearDown(self):
        logger.info('----------------------------后置处理-----------------------------')

        # 还原pg_log文件
        logger.info('----------------------------还原pg_log文件-----------------------------')
        excute_cmd = f'mv {self.DB_LOG_PATH}.testBAK {self.DB_LOG_PATH}'
        logger.info(excute_cmd)
        msg = self.primaryNode.sh(excute_cmd).result()
        logger.info(msg)
        logger.info('----------------------------Reliability_Dbsys_Case184执行完成-----------------------------')
